<?php

namespace App\Http\Controllers\Frontend;


use App\Http\Controllers\Controller;
use App\Logics\NewsLogic;
use App\Logics\SiteLogic;
use App\Models\NewsDesc;
use Illuminate\Support\Facades\Cache;

class BaseController extends Controller
{
    protected $model;
    protected $error;
    protected $assign;

    // 初始化
    public function initialize()
    {

        $option = $this->optLogic();


        /*$myUser = $this->myUser();
        $action = $option->getData('action', 'index', 'trim');
        if(empty($myUser) && (!in_array($action, ['login', 'on-login']))){
            // 如果没有登录
            header("Location: /home/login");
            die;
        }*/

        // 是否ajax请求
        $is_ajax = $this->request->ajax();
        if(empty($is_ajax)){
            // 栏目
            $cates = $this->getCate();
            $tops  = $this->getTop();
            $tags  = $this->getTags();
            $weeks = $this->getWeek();
            // 组件操作
            //  组件：只传递一些常用参数，避免混淆
            $_compData = [];
            $component = new Components($_compData);


            $option->assign('component', $component);
            $option->assign('cates', $cates);
            $option->assign('tops', $tops);
            $option->assign('weeks', $weeks);
            $option->assign('tags', $tags);
            $option->assign('site_name', 'Asia Tech Wire');
        }

        parent::initialize();

    }

    // 获取栏目
    protected function getCate()
    {
        $lists = (new SiteLogic())->cates('rank ASC');

        return $lists;
    }

    // 置顶
    protected function getTop()
    {
        $lists = (new NewsLogic())->setLists('top');

        return $lists;
    }

    // 一周最热 有10分钟的缓存
    protected function getWeek()
    {
        $name  = 'getWeekNewsList';
        $lists = Cache::get($name);
        if(empty($lists)){
            $domain    = env('STYLE_HOST');
            $oldDomain = env('OLD_HOST');
            $start     = strtotime("-80 days");
            $start     = strtotime("-8 days");
            $lists     = (new NewsLogic())->timeList($start, 'virtual_no DESC');
            $descs     = (new NewsDesc())->isCache(true)->getListInIds(array_column($lists, 'id'), '*', 'news_id');
            foreach($descs as $_key => $_desc){
                $number = 0;
                if(strpos($_desc['en_content'], '<img') !== false){
                    $number = 1;
                }

                // 截取第一段
                $en_contents = explode('</p>', $_desc['en_content']);
                $cn_contents = explode('</p>', $_desc['cn_content']);
                $tc_contents = explode('</p>', $_desc['tc_content']);

                // 重新组合 描述
                $descs[$_key]['en_description'] = strip_tags($en_contents[$number] ?? $en_contents[0]);
                $descs[$_key]['cn_description'] = strip_tags($cn_contents[$number] ?? $cn_contents[0]);
                $descs[$_key]['tc_description'] = strip_tags($tc_contents[$number] ?? $tc_contents[0]);
                $descs[$_key]['en_content']     = str_replace($oldDomain, $domain, $_desc['en_content']);
                $descs[$_key]['cn_content']     = str_replace($oldDomain, $domain, $_desc['cn_content']);
                $descs[$_key]['tc_content']     = str_replace($oldDomain, $domain, $_desc['tc_content']);
            }

            // 整理
            foreach($lists as &$item){
                $_newsId = $item['id'];

                // 改变图片域名地址
                if($item['pic']){
                    $item['pic'] = str_replace($oldDomain, $domain, $item['pic']);
                }

                $item['en_content'] = $descs[$_newsId]['en_content'] ?? '';
                $item['cn_content'] = $descs[$_newsId]['cn_content'] ?? '';
                $item['tc_content'] = $descs[$_newsId]['tc_content'] ?? '';
                if(!empty($descs[$_newsId]['en_description'])){
                    $item['en_description'] = strip_tags($descs[$_newsId]['en_description']);
                }
                if(!empty($descs[$_newsId]['cn_description'])){
                    $item['cn_description'] = strip_tags($descs[$_newsId]['cn_description']);
                }
                if(!empty($descs[$_newsId]['tc_description'])){
                    $item['tc_description'] = strip_tags($descs[$_newsId]['tc_description']);
                }
                if($item['en_description']){
                    $item['en_description'] = str_replace("\n", "", $item['en_description']);
                }
                if($item['cn_description']){
                    $item['cn_description'] = str_replace("\n", "", $item['cn_description']);
                }
                if($item['tc_description']){
                    $item['tc_description'] = str_replace("\n", "", $item['tc_description']);
                }
            }

            Cache::put('getWeekNewsList', $lists, 3600); // 10分钟
        }

        return $lists;
    }

    // 标签
    protected function getTags()
    {
        $lists = (new SiteLogic())->tags(10, "number DESC");

        return $lists;
    }

    // 下一页
    protected function nextPage($type, $parameters = [])
    {
        $option = $this->optLogic();
        $page   = $option->getData('page', 1, 'intval');

        //var_dump('控制器 nextPage 方法');
        //var_dump($option->getData());

        return atwUrl($type, $parameters, $page + 1);
    }

    // 展示模板
    protected function dispaly($template = '', $vars = [])
    {
        $option = $this->optLogic();

        // 模板
        if(empty($template)){
            $action   = $option->getData('action', null, 'trim');
            $template = 'frontend.'.$action;
        }

        // STYLE_HOST
        $app_host = $this->request->getSchemeAndHttpHost().'/';
        $option->assign('style_host', env('STYLE_HOST'));
        $option->assign('app_host', $app_host);

        return $option->dispaly($template, $vars, false);
    }

    // 获取用户
    protected function myUser()
    {
        $option = $this->optLogic();
        $info   = $option->session();
        if($info === false){
            return $info;
        }
        if(empty($info)){
            return $info;
        }
        // 组合
        $info['uid']  = $info['id'];
        $this->myUid  = $info['id'];
        $this->myUser = $info;
        $option->assign('myUser', $info);

        return $info;
    }


    // 接口处理失败时调用 404页面
    protected function error(string $message = '操作失败', array $data = [], int $code = ERROR_CODE)
    {
        $msg  = $this->optLogic()->translate($message);
        $data = empty($data) ? [] : $data;
        $json = ['msg' => $msg, 'code' => $code, 'data' => $data,];

        if($this->request->ip() == '127.0.0.1'){
            return $json;
        } else{
            return view('404', $json);
        }
    }

}


